import { Component, OnInit } from '@angular/core';
import {Driver} from "../../shared/model/driver";
import {ActivatedRoute, Router} from "@angular/router";
import {DriverService} from "../../shared/service/driver.service";

@Component({
  selector: 'app-driver-list',
  templateUrl: './driver-list.component.html',
  styleUrls: ['./driver-list.component.css']
})
export class DriverListComponent implements OnInit {

  drivers:Driver[];
  oldDrivers: Driver[];
  selectedDriver: Driver;

  constructor(private route:ActivatedRoute,
              private router:Router,
              private driverservice:DriverService) { }

  ngOnInit() {

    this.getDrivers();

    //筛选符合搜索框中条件的DriverList集合
    this.driverservice.searchEvent.subscribe(param =>{
      let result = this.oldDrivers;
      if(param){
        result = result.filter((r:Driver)=>r.name.indexOf(param)!=-1);
      }
      this.drivers = result;
    });

    this.driverservice.listFreshEvent.subscribe(
      param => {
        if (param) {
          this.getDrivers();
        }
      }
    );
  }

  onSelect(driver: Driver): void {
    this.selectedDriver = driver;
  }

  delDriver(driver: Driver):void {
    if(confirm("确认删除?")){
      this.driverservice.deleteDriver(driver.oid).then(
        res => {
          alert(res.message);
          this.router.navigateByUrl('/driver/new');
          this.driverservice.searchFreshEvent.emit("delete");
          this.getDrivers();
        }
      );
    }
  }

  getDrivers(){
    this.driverservice.getDriverList().then(
      res => {
        this.drivers = res;
        this.oldDrivers = res;
      }
    );
  }

}
